package org.example.myspringboot.controller;


import org.example.myspringboot.pojo.ResponseMessage;
import org.example.myspringboot.pojo.User;
import org.example.myspringboot.pojo.dto.UserDto;
import org.example.myspringboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController//创建一个返回 JSON 数据的 RESTful Web 服务
@RequestMapping("/user")//以将 HTTP 请求映射到对应的处理器方法上。

public class UserController {
@Autowired//Spring 容器会在创建 bean 后调用该方法并注入依赖
IUserService userService;
    @PostMapping//增
    public ResponseMessage add(@Validated @RequestBody UserDto userDto) {
        //@Validated  检查请求参数的有效性，不符合抛出异常
        //@RequestBody 将HTTP请求体中的JSON数据反序列化为User对象
    User newUser=userService.add(userDto);
        return ResponseMessage.success(newUser);
    }

    @GetMapping("/{userId}")//查
    public ResponseMessage get(@PathVariable Integer userId) {
        User newUser=userService.getUser(userId);
        return ResponseMessage.success(newUser);
    }

   @PutMapping
    public ResponseMessage update(@Validated @RequestBody UserDto userDto) {
        //@Validated  检查请求参数的有效性，不符合抛出异常
        //@RequestBody 将HTTP请求体中的JSON数据反序列化为User对象
        User newUser=userService.edit(userDto);
        return ResponseMessage.success(newUser);
    }

    @DeleteMapping("/{userId}")//查
    public ResponseMessage delete(@PathVariable Integer userId) {
        userService.delete(userId);
        return ResponseMessage.success();
    }
}
